package kib.fun.server.connection;

import java.io.IOException;
import java.net.ServerSocket;

/** This inner class will keep listening to incoming connections,
 *  and initiating a ClientThread object for each connection. */

public class StartServerThread extends Thread {
    private boolean listen;
    private Server server = null;

    public StartServerThread(Server server) {
        this.listen = false;
        this.server = server;
    }

    public void run() {
        this.listen = true;
        try {

		/**The following constructor provides a default number of
		* connections -- 50, according to Java's documentation.
		* An overloaded constructor is available for providing a 
		* specific number, more or less, about connections. 
		**/
		
		server.setSsocket(new ServerSocket(server.port));


               while (this.listen) {
		//wait for client to connect//

              server.setSocket(server.getSsocket().accept());
                System.out.println("Client connected");
                try {
                    server.setClientThread(new ClientThread(server.getSocket()));
                    Thread t = 
                         new Thread(server.getClientThread());
                                      server.getClientThread().addObserver(server);
                    server.getClients().addElement(
                       server.getClientThread()
                          );
                    t.start();
                } catch (IOException ioe) {
                    //some error occured in ClientThread //
                }
            }
        } catch (IOException ioe) {
            //I/O error in ServerSocket//
            this.stopServerThread();
        }
    }

    public void stopServerThread() {
        try {
            server.getSsocket().close();
        }
        catch (IOException ioe) {
            //unable to close ServerSocket
        }
        
        this.listen = false;
    }
}
